# -*- coding: utf-8 -*-

import logging
from functools import partial

from django.utils.translation import ugettext_lazy as _
from pipeline.component_framework.component import Component
from pipeline.core.flow.activity import Service, StaticIntervalGenerator
from pipeline.core.flow.io import StringItemSchema

from gcloud.conf import settings
from gcloud.utils.handlers import handle_api_error

logger = logging.getLogger("celery")
class AppPublishSopsExecService(Service):
    __need_schedule__ = True
    interval = StaticIntervalGenerator(5)  # 每隔5秒钟进行重启结果状态轮询

    def inputs_format(self):
        return [
            self.InputItem(
                name=_("进程"), key="proc_id", type="string", schema=StringItemSchema(description=_("进程ID"),),
            ),

        ]

    def outputs_format(self):
        return [
            self.OutputItem(
                name=_("task_ID"),
                key="task_id",
                type="string",
                schema=StringItemSchema(description=_("任务ID")),
            ),
        ]

    def execute(self, data, parent_data):
        executor = parent_data.get_one_of_inputs("executor")
        biz_cc_id = data.get_one_of_inputs("biz_cc_id", parent_data.inputs.biz_cc_id)

        proc_id = data.get_one_of_inputs("proc_id")

        #exec sops: result_id
        #job_id = job_result["data"]["job_id"]
        data.set_outputs("task_id", executor)

        return True

    def schedule(self, data, parent_data, callback_data=None):
        """
        轮询结果
        data: act.component.inputs.KeyFoo = Var(type=Var.PLAIN, value="ValFoo dict or str")
        parent_data: may be same as [root inputs]
        """
        executor = parent_data.get_one_of_inputs("executor")
        biz_cc_id = data.get_one_of_inputs("biz_cc_id", parent_data.inputs.biz_cc_id)
        proc_id = data.get_one_of_inputs("proc_id")
        sops_task_vars_name = data.get_one_of_inputs("sops_task_vars_name")
        sops_task = data.get_one_of_inputs("sops_task")
        #exec sops: result_id
        #job_id = job_result["data"]["job_id"]
        self.logger.info("[my celery log] app publish sops exec schedule "
                         "executor: {executor} "
                         "biz_cc_id: {biz_cc_id} "
                         "sops_task_vars_name: {sops_task_vars_name} "
                         "sops_task: {sops_task}"
                         .format(executor=executor,biz_cc_id=biz_cc_id,sops_task_vars_name=sops_task_vars_name,sops_task=sops_task))

        # 停止轮询
        self.finish_schedule()

        # 结束信号：成功
        return True

    pass

class AppPublishSopsExecComponent(Component):
    name = _("应用发布SOPS")
    code = "app_publish_sops_exec"
    bound_service = AppPublishSopsExecService
    form = ""
    desc = _("从应用发布数据调用sops接口发布")
